package com.example.client;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.example.aidl.Book;
import com.example.aidl.IBookManager;
import com.example.aidl.IOnBookListener;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final int MESSAGE = 1;
    private IBookManager mIBookManager;
    private int i = 0;
    private IOnBookListener mBookListener = new IOnBookListener.Stub() {
        @Override
        public void NewBookArrived(Book book) throws RemoteException {
            mHandler.obtainMessage(MESSAGE, book).sendToTarget();
        }
    };
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE:
                    //收到新书
                    Book book = (Book) msg.obj;
                    i++;
                    Log.e(TAG, "client receive book" + i + "::" + book.getBookName());
                    break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            IBookManager manager = IBookManager.Stub.asInterface(iBinder);
            try {
                mIBookManager = manager;
                List<Book> books = manager.getBookList();//获取服务端图片列表并toast
                for (Book book : books) {
                    Toast.makeText(MainActivity.this, book.getBookName(), Toast.LENGTH_SHORT).show();
                }
                manager.addBook(new Book(3, "Android开发艺术探索"));//添加新书
                manager.addBook(new Book(4, "Android开发艺术探索2"));//添加新书
                manager.addBook(new Book(5, "Android开发艺术探索3"));//添加新书
                List<Book> newList = manager.getBookList();

                manager.registerListener(mBookListener);//注册新书推送

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (!MainActivity.this.isFinishing()) {
                            if (mIBookManager != null) {
                                try {
                                    mIBookManager.addBook(new Book(100, "我是新书"));
                                    Thread.sleep(2500);
                                } catch (RemoteException | InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }).start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent1 = new Intent();
        intent1.setAction("android.intent.action.BOOK_AIDL_MESSAGE");
        Intent intent = new Intent(achieveExplicitFromImplicitIntent(this, intent1));
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

//        Intent intent = new Intent(this, BookManagerService.class);
//        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);//绑定服务
    }

    @Override
    protected void onDestroy() {
        if (mIBookManager != null && mIBookManager.asBinder().isBinderAlive()) {
            try {
                Log.e(TAG, "unregister listener" + mBookListener);
                mIBookManager.unregisterListener(mBookListener);//取消新书推送消息
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }

    public Intent achieveExplicitFromImplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);

        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }

        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        Log.d(TAG, "packageName = " + packageName);
        Log.d(TAG, "className = " + className);
        ComponentName component = new ComponentName(packageName, className);

        Intent explicitIntent = new Intent(implicitIntent);

        explicitIntent.setComponent(component);
        return explicitIntent;
    }
}